package com.work.daily;

import java.util.*;

/**
 * title : 前 K 个高频元素
 * content : 输入: nums = [1,1,1,2,2,3], k = 2 ;输出: [1,2]
 * solution : 利用hashmap来统计,利用collections的sort对value进行排序.
 * link :
 * Created by suk on 2020/9/7.
 */
public class D10_TopKFrequent_347_01 {

    public static void main(String[] args) {
        int[] nums = {1, 2, 1, 3, 2, 2};
        int k = 2;
        D10_TopKFrequent_347_01 d10 = new D10_TopKFrequent_347_01();
        System.out.println(Arrays.toString(d10.topKFrequent(nums, k)));
    }
    public int[] topKFrequent(int[] nums, int k) {

        Map<Integer, Integer> map = new HashMap<>();
        for (int num : nums) {
            if (map.containsKey(num)) {
                int i = map.get(num);
                map.put(num, new Integer(i + 1));
            } else {
                map.put(num, new Integer(1));
            }
        }

        // 对value进行排序
        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<Integer, Integer>>() {
            @Override
            public int compare(Map.Entry<Integer, Integer> o1, Map.Entry<Integer, Integer> o2) {
                return o2.getValue() - o1.getValue();
            }
        });
        int[] result = new int[k];
        for (int i = 0; i < k; i++) {
            result[i] = list.get(i).getKey();
        }

        return result;
    }
}
